% function estimaLoopSingle
%% 7. Begin Estimation Loop
parfor ii=1:priorStru.numStartVals;
    
    %% 7a) Parvecmode is the mode
    parvecmode=zeros(numpar, 1);
    parvecmode(posStru.param.cal)=parStru.cal;
    
    %% 7b) Optimization Routine, output is optimOut
    disp(['Starting Value',num2str(ii)]);  
    
    % Cannot add this call here, parfor does not like having 
    % loop_logPost(ii,1) and loop_logPost(ii,2)
    %     [loop_logPost(ii,1),loop_logLikel(ii,1),loop_logPrior(ii,1)]=...
    %         feval(filterStru.funcPost,loopStru.parStartMat(posStru.param.est,ii),parStru,...
    %         posStru,model,dataStru,prpar,prss,filterStru,flags);
        
    optimOut=feval(estimopt.funcHandle,loopStru.parStartMat(posStru.param.est,ii),estimopt,...
        parStru,posStru,model,dataStru,prpar,prss,filterStru,flags,struInOpt);
    
    %% 7c) Assing fields of optimOut
    parvecmode(posStru.param.est)=optimOut.mode;
    parestmat(:,ii)=optimOut.mode;
    loop_parMode(:,ii)=parvecmode;
    loop_std(:,ii)=sqrt(diag(optimOut.Hessian));
    loop_hessian(:,:,ii)=optimOut.Hessian;
    
    %% 7d) Compute Posterior (old syntaxis, replace by passing structure)
    [loop_logPost(ii,2),loop_logLikel(ii,2),loop_logPrior(ii,2)]=...
        feval(filterStru.funcPost,parestmat(:,ii),parStru,...
        posStru,model,dataStru,prpar,prss,filterStru,flags);
    
    try
        disp(['Result from estimation ',feval(@num2str,ii)]);
        feval(@printcell,[parnames(posStru.param.est) feval(@num2cprec,optimOut.mode)]);
        dispaj('Log Posterior = ',loop_logPost(ii,2));
        dispaj('Log Likelihood= ',loop_logLikel(ii,2));
    catch
        lasterr
    end
    loop_exitFlag(ii)=optimOut.exitFlag;
    loop_iterations(ii)=optimOut.iterations;
    loop_time(ii)=optimOut.time/60; 

end